<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 头部 -->
      <PageTools :show-before="true">
        <span slot="before">共{{ page.total }}条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import?type=user')">导入</el-button>
          <el-button size="small" type="danger" @click="exportData">导出</el-button>
          <el-button
            icon="plus"
            size="small"
            type="primary"
            :disabled="CheckPermission('POINT-USER-ADD')"
            @click="showDialog = true"
          >新增员工</el-button>
        </template>
      </PageTools>
      <!-- 表格和分页 -->
      <el-card v-loading="loading">
        <el-table border :data="list">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="头像" align="center">
            <template slot-scope="{row}">
              <img v-imageerror="require('@/assets/common/bigUserHeader.png')" :src="row.staffPhoto ? row.staffPhoto : require('@/assets/common/bigUserHeader.png') " style="border-radius: 50%; width: 100px; height: 100px; padding: 10px" alt="">
            </template>
          </el-table-column>
          <el-table-column label="姓名" align="center" sortable="" prop="username" />
          <el-table-column label="工号" align="center" sortable="" prop="workNumber" />
          <el-table-column label="手机号" align="center" sortable="" prop="mobile" />
          <el-table-column label="聘用形式" align="center" sortable="" prop="formOfEmployment" :formatter="formatEmployment" />
          <el-table-column label="部门" align="center" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" align="center" sortable="">
            <!-- 作用域插槽 -->
            <template slot-scope="{row}">{{ row.timeOfEntry | formatDate }}</template>
          </el-table-column>
          <el-table-column label="账户状态" align="center" sortable="">
            <template slot-scope="{row}">
              <!-- 根据当前状态来确定是否打开开关 -->
              <el-switch :value="row.enableState===1" />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template slot-scope="{row}">
              <el-button
                type="text"
                size="small"

                @click="$router.push(`/employees/detail/${row.id}`)"
              >查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
              <el-button
                type="text"
                size="small"
                :disabled="!CheckPermission('DEL-USER')"
                @click="delEmployee(row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="prev, pager, next"
            :page-size="page.size"
            :current-page="page.page"
            :total="page.total"
            @current-change="changePage"
          />
        </el-row>
      </el-card>
    </div>
    <!-- 放置新增组件 -->
    <AddEmployee :show-dialog.sync="showDialog" />
    <!-- 放置角色分配组件 -->
    <AssignRole ref="assignRole" :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
// 引入枚举数据
import EmployeeEnum from '@/api/constant/employees'
// 引入组件
import AddEmployee from './components/add-empoyee'
import AssignRole from './components/assign-role'
import { formatDate } from '@/filters'
export default {
  components: {
    AddEmployee, AssignRole
  },
  data() {
    return {
      showRoleDialog: false, // 控制角色弹层
      showDialog: false, // 弹层
      loading: false, // 加载进度
      list: [],
      page: {
        page: 1,
        size: 10,
        total: 0 // 总数
      },
      userId: null
    }
  },
  created() {
    // 发起请求
    this.getEmployeeList()
  },
  methods: {
    // 角色事件
    async editRole(id) {
      // props 传值是异步
      this.userId = id
      // 父组件调用子组件方法
      await this.$refs.assignRole.getUserDatailById(id)
      this.showRoleDialog = true
    },
    // 封装员工列表数据请求
    async getEmployeeList() {
      this.loading = true
      const { total, rows } = await getEmployeeList(this.page)
      this.page.total = total
      this.list = rows
      this.loading = false
    },
    // 分页事件
    changePage(newPage) {
      this.page.page = newPage
      this.getEmployeeList()
    },
    // 格式化聘用形式
    formatEmployment(row, column, cellValue, index) {
      // 获取枚举数组
      const list = EmployeeEnum.hireType
      const obj = list.find(item => item.id === cellValue)
      // 应该返回 返回的值就会被渲染到表格上
      return obj ? obj.value : '未知'
    },
    // 删除事件
    async delEmployee(id) {
      try {
        await this.$confirm('你确定要删除该员工吗')
        await delEmployee(id) // 删除
        this.getEmployeeList() // 刷新
        this.$message.success('删除员工成功')
      } catch (error) {
        console.log(error)
      }
    },
    // 导出事件
    exportData() {
      // 表头对应的关系 中文和英文对应
      const headers = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      // 懒加载
      import('@/vendor/Export2Excel').then(async excel => {
        const { rows } = await getEmployeeList({ page: 1, size: this.page.total })
        const data = this.formatJson(headers, rows)

        excel.export_json_to_excel({
          header: Object.keys(headers),
          data,
          filename: '员工信息表',
          autoWidth: true,
          bookType: 'xlsx'
        })
      })
    },
    // 该方法负责将数组转化成二维数组
    formatJson(headers, rows) {
      // 首先遍历数组
      // [{username:'张三'},{},{}] => [['张三'],[],[]]
      return rows.map(item => {
        // item 是对象 ==>转化成只有值的数组 ==> 数组值的顺序依赖headers {username:'张三'}
        // Object.keys(headers) ==>['姓名','手机号']
        return Object.keys(headers).map(key => {
          // 判断时间格式
          if (headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime') {
            return formatDate(item[headers[key]]) // 返回格式化之前的时间
          } else if (headers[key] === 'formOfEmployment') {
            var en = EmployeeEnum.hireType.find(obj => obj.id === item[headers[key]])
            return en ? en.value : '未知'
          }
          return item[headers[key]] // 得到 ['张三','1396656','2020','1','10021']
        })
      })
    }

  }

}
</script>

<style>

</style>
